//
//  DDHomeVc.swift
//  SinaMicroBlog
//
//  Created by dqw on 15/7/28.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit




class DDHomeVc: DDBaseTableVC {

    var statuses: [DDStatus]? {
        didSet {
            tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        if !DDUserAccount.isUserLogOn {
            visitorLoginView?.configView(true, message: "关注一些人，回这里看看有什么惊喜", iconName: "visitordiscover_feed_image_smallicon")
            return
        }
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "browsePicture:", name: DDPictureBrowserNotification, object: nil)
    configureTableView()
    loadData()
        
    }
    // 浏览图片方法
    func browsePicture(not: NSNotification) {
        let dict = not.userInfo!
        
        guard  let indexPath = dict[DDPictureBrowserIndexKey]  as? NSIndexPath else {
            return
        }
        guard let  imageUrls = dict[DDPictureBrowserUrlsKey] as? [NSURL]  else {
            return
        }
   
        guard  let picView = not.object as? DDStatusCellPictureView  else {
            return
        }
        
        indexPathOnBegin = indexPath
        statusPicView  = picView
        
        transitionImageView.sd_setImageWithURL(imageUrls[(indexPathOnBegin!.item)])
        let pictureBrowserVC = DDPictureBrowserVC(index: indexPathOnBegin!.item, imageUrls: imageUrls)
        pictureBrowserVC.transitioningDelegate = self
        pictureBrowserVC.modalPresentationStyle = UIModalPresentationStyle.Custom
        presentViewController(pictureBrowserVC, animated: true
            , completion: nil)
    }
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

// MARK: - tableviewCell的高度，预估高度，和自动高度冲突。
    private func configureTableView() {
        self.automaticallyAdjustsScrollViewInsets = false
        tableView.registerClass(DDStatusForwardCell.self, forCellReuseIdentifier: DDStatusCellId.forwardId.rawValue)
        tableView.registerClass(DDStatusNormalCell.self, forCellReuseIdentifier: DDStatusCellId.normalId.rawValue)
        tableView.estimatedRowHeight = 300
//        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        refreshControl = DDRefresh()
//        refreshControl = UIRefreshControl()
        // edgeInsert
        tableView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
    }
    
    private var pullDownFlag = false
    
     func loadData() {
        // 自动计划刷新下拉的动画。
        refreshControl?.beginRefreshing()
        
        var sinceId = self.statuses?.first?.id ?? 0
        var maxId = 0
        
        if pullDownFlag {
            sinceId = 0
            maxId = (statuses?.last?.id)! ?? 0
        }
        
        DDStatus.loadStatuses(sinceId, max_id: maxId){(statuses, error) -> Void in
            
            self.refreshControl?.endRefreshing()
            // MARK: -  解决 出错后的bug。要将每个分支都过一遍。
            self.pullDownFlag = false

            if error != nil
            {
                print(error)
                return
            }
            
            let count = statuses?.count ?? 0
            
            if sinceId > 0 {
                self.pullTipLabel(count)
            }
            print("得到\(count)")
            if count == 0 {
                return
            }
        
            if sinceId > 0 {
                
                self.statuses = statuses! + self.statuses!
            }else if maxId > 0 {
                self.statuses! += statuses!
            }else {
                self.statuses = statuses!
            }
        }
    }
    
    //  MARK: - 数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // 在Swift里面要时刻注意数据类型。空的时候，给个默认值。
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let status = statuses![indexPath.item]
        let cell = tableView.dequeueReusableCellWithIdentifier(DDStatusCellId.cellId(status)!) as! DDStatusCell
        cell.status = status
        
        // 巧妙？？
        if indexPath.item == statuses!.count - 1 {
            pullDownFlag = true
        loadData()
        }
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // 缓存行高，因为行高总共也没有占用多少空间。
        let status = statuses![indexPath.row]
        if let H = status.rowHeight {
//            print("缓存行高")
            return H
        }
        // 如果在该代理方法里面调用xxx forindexpath，则其会调用该代理方法本身，循环调用。
       let  cell = tableView.dequeueReusableCellWithIdentifier(DDStatusCellId.cellId(status)!) as! DDStatusCell
        status.rowHeight = cell.rowHeight(statuses![indexPath.item])
       return status.rowHeight!
}

    private func pullTipLabel(count: Int) {
        // 忘了是position还是positions
        if (tipLabel.layer.animationForKey("position")) != nil  {
            return
        }
        print(tipLabel.layer.animationKeys())
        tipLabel.text = count == 0 ? "没有新的微博" : " 刷到了\(count)条微博"
        let rect: CGRect = tipLabel.frame
  
        UIView.animateWithDuration(2.0, animations: { () -> Void in
            UIView.setAnimationRepeatAutoreverses(true)
            self.tipLabel.frame = CGRectOffset(rect, 0, 3 * rect.height)
            }) { (_) -> Void in
                self.tipLabel.frame = rect
        }
    }
    
    private lazy var tipLabel:UILabel = {
        
        let H: CGFloat = 44
        // 2 是为了消除毛边效果。
        let label = UILabel(frame: CGRect(x: 0, y:  -2 * H, width:UIScreen.mainScreen().bounds.width, height: H))
        label.backgroundColor = UIColor.redColor()
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Center
        // 可以添加到navbar里面，巧妙。
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        return  label
        
        }()
    var isPresented = false
    private lazy var transitionImageView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        
        return iv
    }()
    var statusPicView: DDStatusCellPictureView?
    var indexPathOnBegin: NSIndexPath?
}

extension DDHomeVc : UIViewControllerTransitioningDelegate {
    
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        return self
    }
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }
}

extension DDHomeVc: UIViewControllerAnimatedTransitioning {
    
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 2.0
    }
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
    
        if isPresented {
            
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)
            
            let fromRect = statusPicView?.frameOfThumbnailImageInHomeView(indexPathOnBegin!)
            let toRect = statusPicView?.frameOfLargeImageInHomeView(indexPathOnBegin!)
//            toView?.alpha = 0
//            transitionContext.containerView()?.addSubview(toView!)

            transitionImageView.frame = fromRect!
            transitionContext.containerView()?.addSubview(transitionImageView)
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
//                toView?.alpha = 1
                self.transitionImageView.frame = toRect!
                }, completion: { (_) -> Void in
                    self.transitionImageView.removeFromSuperview()
                    transitionContext.containerView()?.addSubview(toView!)
                    transitionContext.completeTransition(true)
            })
            return
        }
        
            let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
            let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! DDPictureBrowserVC
            let currentIndexPath = fromVC.currentIndexPath()
            let iv = fromVC.currentImageView(currentIndexPath)
            let toRect = statusPicView?.frameOfThumbnailImageInHomeView(currentIndexPath)
            iv.center = (fromView?.center)!
            iv.center.x -= 10
            let scale = fromView!.transform.a
            iv.transform = CGAffineTransformScale(iv.transform, scale, scale)

        
            fromView?.removeFromSuperview()
            transitionContext.containerView()?.addSubview(iv)
        
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                fromView?.alpha = 0
                iv.frame = toRect!
                }, completion: { (_) -> Void in
//                    fromView?.removeFromSuperview()
                    iv.removeFromSuperview()
                    transitionContext.completeTransition(true)
            })
        
    }
}